package handle

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"
	"strings"
	"time"

	"github.com/PuerkitoBio/goquery"
	"golang.org/x/text/encoding/simplifiedchinese"
	"golang.org/x/text/transform"
)

// 	goqueryGBKImg("")
//Get https://detail.tmall.com/item.htm?id=555046256379&tbpm=3: stopped after 10 redirects

func goqueryGBKImg(pageURL string, l string) {
	fmt.Println("start!")
	imgAttr, imgSize := getImginfo(pageURL)
	id := getid(pageURL)
	resp, err := http.Get(pageURL)
	if err != nil {
		log.Fatal(err)
	}
	doc, err := goquery.NewDocumentFromReader(transform.NewReader(resp.Body, simplifiedchinese.GBK.NewDecoder()))
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	// rd := data.FavoriteGoods{}
	doc.Find("#J_UlThumb li").Each(func(i int, s *goquery.Selection) {
		p, _ := s.Find("a img").Attr(imgAttr)              // src or data-src  tmall or taobao
		pic := "https:" + strings.Split(p, "_"+imgSize)[0] // 60x60 or 50x50   tmall or taobao

		fmt.Printf("Review %d: %s - %s\n", i, "img", pic)

		x := strings.LastIndexAny(pic, "/")
		filename := pic[x+1:]
		if !strings.Contains(filename, ".jpg") {
			filename = filename + ".jpg"
		}
		// if i == 0 {
		// 	intid, _ := strconv.ParseInt(id, 10, 64)
		// 	rd.GoodsID = intid
		// 	rd.GoodsURL = pageURL
		// 	rd.PicFirst = filename
		// 	rd.Remark = ""
		// }
		downloadfile(pic, l+`-`+id, filename)
	})
	// data.Mydb.AutoMigrate(rd)
	// if err := data.Mydb.Create(&rd).GetErrors(); len(err) > 0 {
	// 	fmt.Println(len(err), err)
	// }
	fmt.Println("end!")
}

func downloadfile(imgsrc string, id string, filename string) {
	fmt.Println(time.Now(), filename, "开始下载!")
	res, err := http.Get(imgsrc)
	if err != nil {
		log.Fatal(err)
	} else {
		os.MkdirAll("picture/"+id, 0777)
		file, err := os.Create("picture/" + id + "/" + filename)
		if err != nil {
			log.Fatal(err)
		} else {
			io.Copy(file, res.Body)
			fmt.Println("下载完成!")
		}
	}
	//time.Sleep(time.Second * 10)
}

func getid(pageURL string) string {
	u, err := url.Parse(pageURL)
	if err != nil {
		panic(err)
	}
	urlParam := u.Query()
	return string(urlParam["id"][0])
}

func getImginfo(pageURL string) (imgAttr string, imgSize string) {
	if strings.Contains(pageURL, "taobao") {
		return "data-src", "50x50"
	} else if strings.Contains(pageURL, "tmall") {
		return "src", "60x60"
	} else {
		return
	}
}
